package pt.utl.ist.project_ccu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeMap;

import pt.utl.ist.project_ccu.android_libs.Photo;
import pt.utl.ist.project_ccu.android_libs.SavedData;
import pt.utl.ist.project_ccu.android_libs.Tag;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class AddTags extends Activity {

	HashMap<String,Button> buttons;
	Button donetagging;
	Button backbuttonupload;

	private final int MAX_NUMBER_OF_TAGS = 5;
	TableLayout _tl;
	Spinner _spinner1;
	TextView inputField;
	Button _addTagsButton;
	TreeMap<Integer,EditText> _textviewMap = new TreeMap<Integer,EditText>();
	TreeMap<Integer,String> _tagSelectedMap = new TreeMap<Integer,String>();
	TreeMap<Integer,TableRow> _tableRows = new TreeMap<Integer,TableRow>();
	ArrayList<Integer> _imagesIds;

	TableRow _buttonTableRow;
	Integer _spinnerCount = 0;
	int _tagsLimit = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_add_tags);
		_imagesIds =  getIntent().getIntegerArrayListExtra("idImages");
		setupButtons();
		SavedData.getInstance().updateActivity(this);
		_addTagsButton = new Button(this);
		_addTagsButton.setBackgroundResource(R.drawable.another_add_icon);
		_buttonTableRow = createButtonRow();
		_addTagsButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				createRow();

			}
		});
		_tl = (TableLayout) findViewById(R.id.tableLayout);
		createRow();
		setDeleteButtonVisibility(false);

		Log.w("Meu Ouput", _tl.getChildCount()+ "");

	}

	public void setupButtons() {
		buttons = new HashMap<String,Button>();

		donetagging = (Button) findViewById(R.id.donetagging);

		buttons.put("upload", donetagging);
		buttons.put("backbuttonupload", backbuttonupload);

		donetagging.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				ArrayList<Photo> photos = new ArrayList<Photo>();
				Set<Integer> keys = _tagSelectedMap.keySet();

				for (Integer id : _imagesIds ) {
					photos.add(new Photo(id));
				}
				for(Integer i : keys) {
					String tagType = _tagSelectedMap.get(i);
					String tagName = _textviewMap.get(i).getText().toString();
					Log.w("Meu Output", tagType + " " + tagName);
					if(!tagName.equals("") || tagName != null) {
						SavedData.getInstance().addTag(tagType, tagName);
					}

				}
				for(Photo p : photos) {
					for(Integer i : keys) {
						String tagType = _tagSelectedMap.get(i);
						String tagName = _textviewMap.get(i).getText().toString();
						if( !tagName.equals("") || tagName != null) {
							p.addTag(new Tag(tagType,tagName));
						}
					}
				}
				for(Photo p : photos) {
					SavedData.getInstance().addPhoto(p);
				}
				Intent intent = new Intent(getApplicationContext(), PhotoToAlbum.class);
				intent.putExtra("photos", photos);
				startActivity(intent);
			}
		}); 
	}

	private void addRow() {
		int[] screenDimensions = SavedData.getInstance().getScreenDimensions();
		int spinnerWidth = (int) (screenDimensions[0] * 0.4);
		int spinnerWidth_EditText = (int) (screenDimensions[0] * 0.5);
		TableRow tr = new TableRow(this);
		_tableRows.put(_spinnerCount, tr);
		if(_tl.getChildCount() > 1) {
			_tl.removeViewAt(_tl.getChildCount() - 1);
		}
		Spinner tagType = new Spinner(this);
		tagType.setTag(_spinnerCount);
		tagType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {

				Integer spinnerNumber = (Integer) adapterView.getTag();
				String tag = adapterView.getItemAtPosition(pos).toString();
				_tagSelectedMap.put(spinnerNumber, tag);
			} 

			public void onNothingSelected(AdapterView<?> adapterView) {
				return;
			} 
		}); 
		ArrayList<String> tagsTypes =  (ArrayList<String>) SavedData.getInstance().getAllTags();
		ArrayAdapter<String> tagTypesList = new ArrayAdapter<String>(this,R.layout.spinner_item,tagsTypes);
		tagTypesList.setDropDownViewResource(R.layout.spinner_dropdown_item);
		tagType.setAdapter(tagTypesList);
		EditText tagName = new EditText(this);
		
		//limite de caracteres
		InputFilter[] filters = new InputFilter[1];
        filters[0] = new InputFilter.LengthFilter(12); //Limite = 12
        tagName.setFilters(filters);

        tagName.setTag(_spinnerCount);
		_textviewMap.put(_spinnerCount,tagName);

		TableRow.LayoutParams params1 = new TableRow.LayoutParams(
				spinnerWidth,
				TableRow.LayoutParams.FILL_PARENT);
		TableRow.LayoutParams params2 = new TableRow.LayoutParams(
				spinnerWidth_EditText,
				TableRow.LayoutParams.FILL_PARENT);
		TableRow.LayoutParams params3 = new TableRow.LayoutParams(
				TableRow.LayoutParams.FILL_PARENT,
				TableRow.LayoutParams.FILL_PARENT);
		tr.addView(tagType, params1);
		tr.addView(tagName, params2);
		tr.addView(new MyRelativeLayout(this,_spinnerCount),params3);
		TableLayout.LayoutParams trParams = new TableLayout.LayoutParams(
				TableLayout.LayoutParams.FILL_PARENT,
				TableLayout.LayoutParams.FILL_PARENT);
		_tl.addView(tr, trParams);
		TableLayout.LayoutParams tr2Params = new TableLayout.LayoutParams(
				TableLayout.LayoutParams.WRAP_CONTENT,
				TableLayout.LayoutParams.WRAP_CONTENT);
		_tl.addView(_buttonTableRow,tr2Params);


		if(_tl.getChildCount() > 2 ) {
			setDeleteButtonVisibility(true);
		}
		_spinnerCount++;
		_tagsLimit++;
		if(_tagsLimit >= MAX_NUMBER_OF_TAGS) {
			_addTagsButton.setVisibility(View.GONE);
		}
	}

	private void createRow() {
		_tagSelectedMap.put(_spinnerCount, "");
		addRow();

	}

	protected void setDeleteButtonVisibility(boolean visi) {
		for(int i = 0; i < _tl.getChildCount(); i++) {
			TableRow tr = (TableRow) _tl.getChildAt(i);
			if(tr.getChildCount() == 3) {
				Button button = (Button) ((RelativeLayout)tr.getChildAt(2)).getChildAt(0);
				if(visi) {
					button.setVisibility(View.VISIBLE);
				}
				else {
					button.setVisibility(View.GONE);
				}
			}
		}
	}

	private TableRow createButtonRow() {
		FrameLayout fl = new FrameLayout(this);
		int[] screenDimensions = SavedData.getInstance().getScreenDimensions();
		int buttonSize = (int) (screenDimensions[0] * 0.1);
		TableRow tr = new TableRow(this);
		TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,TableRow.LayoutParams.FILL_PARENT);
		fl.addView(_addTagsButton, params);
		tr.addView(fl);
		ViewGroup.LayoutParams parB = _addTagsButton.getLayoutParams();
		parB.height = buttonSize;
		parB.width = buttonSize;
		_addTagsButton.setLayoutParams(parB);

		return tr;
	}

	public class DeleteButton extends Button {

		public DeleteButton(Context context, int id) {
			super(context);
			this.setId(id);
			this.setBackgroundResource(R.drawable.close_icon);
			final int buttonId = this.getId();
			this.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					_tagsLimit--;
					if(_tagsLimit < MAX_NUMBER_OF_TAGS) {
						_addTagsButton.setVisibility(View.VISIBLE);
					}
					if(_tl.getChildCount() > 2) {
						_tagSelectedMap.remove(buttonId);
						_textviewMap.remove(buttonId);
						_tl.removeView(_tableRows.get(buttonId));	
						_tableRows.remove(buttonId);
					}
					if(_tl.getChildCount() == 2) {
						setDeleteButtonVisibility(false);
					}
				}
			});
		}
	}

	public class MyRelativeLayout extends RelativeLayout {

		public MyRelativeLayout(Context context, int id) {
			super(context);
			View dl = new DeleteButton(context, id);
			addView(dl);
			RelativeLayout.LayoutParams parB = (RelativeLayout.LayoutParams) dl.getLayoutParams();
			int[] screenDimensions = SavedData.getInstance().getScreenDimensions();
			int buttonSize = (int) (screenDimensions[0] * 0.1);
			parB.height = buttonSize;
			parB.width = buttonSize;
			parB.addRule(RelativeLayout.CENTER_IN_PARENT, 1);
			dl.setLayoutParams(parB);

		}


	}

}
